package com.innjia.app.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.innjia.app.annotation.LoginRequired;
import com.innjia.base.annotation.SysLog;
import com.innjia.base.enums.HardwareEnum;
import com.innjia.base.utils.PageUtils;
import com.innjia.base.utils.Result;
import com.innjia.base.utils.ValidatorUtils;
import com.innjia.sys.entity.HouseAuthImageEntity;
import com.innjia.sys.entity.HouseEntity;
import com.innjia.sys.entity.HouseImageEntity;
import com.innjia.sys.entity.UserLandlordEntity;
import com.innjia.sys.service.ContractInfoService;
import com.innjia.sys.service.HouseAuthImageService;
import com.innjia.sys.service.HouseImageService;
import com.innjia.sys.service.HouseService;
import com.innjia.sys.service.impl.UserLandlordServiceImpl;

/**
 */
@Controller(value="appHouseController")
@RequestMapping("/app/house")
public class HouseController {
	
	 private static Logger logger = LoggerFactory.getLogger(HouseController.class);
	
    @Autowired
    private HouseService houseService;

    @Autowired
    private HouseImageService houseImageService;
    
    @Autowired
    private UserLandlordServiceImpl landlordService;
    
    @Autowired
    private HouseAuthImageService authImageService;
    
    @Autowired
    private ContractInfoService contractInfoService;

    @RequestMapping(value = "apply",method = RequestMethod.POST)
    @ResponseBody
    @LoginRequired
    public Result apply(@RequestBody HouseEntity houseEntity){

        houseService.apply(houseEntity);
        return Result.ok();
    }

    @RequestMapping("/{id}")
    @ResponseBody
    @LoginRequired
    @SysLog("获取房源详情")
    public Result houseInfo(@PathVariable String id){
    	logger.info("===========appHouseController.houseInfo()start============");
        Map<String, Object> result;
		try {
			result = new HashMap<String, Object>();
			HouseEntity entity = houseService.houseInfo(id);
			if(entity == null) {
				logger.error("通过房源id:" + id + ",查找houseInfo失败");
				return Result.error("1","通过房源id:" + id + ",查找houseInfo失败");
			}
			//如果是子房源，则没有图片信息，需要将父房源的图片信息取出，放入子房源中
			if(StringUtils.isNotBlank(entity.getParentId())) {
				List<HouseImageEntity> houseImages = this.houseImageService.queryListByHouseId(entity.getParentId());
				if(ValidatorUtils.isEmpty(houseImages)) {
					houseImages = new ArrayList<HouseImageEntity>();
					logger.info("通过房源id:" + id + ",未找到对应的房源照片信息");
				}
				entity.setHouseImages(houseImages);
			}
			//添加房东信息
			UserLandlordEntity landlord = new UserLandlordEntity();
			UserLandlordEntity model = landlordService.queryObject(entity.getOwnerId());
			if(model == null) {
				logger.error("通过房源id:" + id + ",查找房东失败");
				return Result.error("1","通过房源id:" + id + ",查找房东失败");
			}
			landlord.setPhone(model.getPhone());
			landlord.setUserName(model.getUserName());
			entity.setLandlord(landlord);
			//添加产权照片信息:只有父房源才有产权照片，所以这里添加的也是父房源的产权照片信息
			List<HouseAuthImageEntity> authImages = null;
			if(ValidatorUtils.isEmpty(entity.getParentId())){
				//父房源，直接通过自己的id查询产权照片
				authImages = authImageService.queryListByHouseId(entity.getId());
			}else{
				authImages = authImageService.queryListByHouseId(entity.getParentId());
			}
			if(ValidatorUtils.isEmpty(authImages)) {
				authImages = new ArrayList<HouseAuthImageEntity>();
				logger.info("通过房源id:" + id + ",未找到对应的产权照片信息");
			}
			entity.setHouseAuthImages(authImages);
			//设置 设施classes 用于APP渲染图标
			entity.setHardwaresClass(HardwareEnum.getHardwareClass(entity.getHardware()));
			result.put("data",entity);
			logger.info("===========appHouseController.houseInfo()end============");
			return Result.ok(result);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("1", "获取房源信息失败，请重试");
		}
    }
    
    @RequestMapping(value = "detail",method = RequestMethod.GET)
    @ResponseBody
    @LoginRequired
    //@RequiresPermissions("sys:house:query")
    @SysLog("获取房源详情")
    public Result detail(HttpServletRequest request) {
    	logger.info("===========appHouseController.detail()start============");
    	Result result = new Result();
    	String  houseId= request.getParameter("houseId");//
    	if(StringUtils.isBlank(houseId)) {
    		logger.info("查询房源详情失败，houseId不能为空");
    		return Result.error("1", "查询房源详情失败，houseId不能为空");
    	}
    	try {
			HouseEntity entity = this.houseService.queryDetailById(houseId);
			if(entity == null) {
				logger.info("通过房源id:" + houseId + ",未找到对应房源");
				return Result.error("1","通过房源id:" + houseId + ",未找到对应房源");
			}
			//如果整租，将自己添加到children中
			if(StringUtils.equals(entity.getRentType(), "整租")) {
				//父房源
				List<HouseEntity> children = new ArrayList<>();
				HouseEntity model = new HouseEntity();
				model.setId(entity.getId());
				model.setRentStatus(entity.getRentStatus());
				model.setSerialNum(entity.getSerialNum());
				model.setDoor(entity.getDoor());
				model.setBuildingArea(entity.getBuildingArea());
				model.setDirect(entity.getDirect());
				model.setRentalPrice(entity.getRentalPrice());
				children.add(model);
				entity.setChildren(children);
			}
			//设置 设施classes 用于APP渲染图标
			entity.setHardwaresClass(HardwareEnum.getHardwareClass(entity.getHardware()));

			result.put("entity", entity);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			logger.info("通过房源id:" + houseId + ",查询房源详情异常,请联系管理员");
			return Result.error("1","通过房源id:" + houseId + ",查询房源详情失败,请稍后再试");
		}
    	logger.info("===========appHouseController.detail()end============");
    	return result;
    }
    
    @RequestMapping(value = "list",method = RequestMethod.GET)
    @ResponseBody
    @LoginRequired
    public Result list(HttpServletRequest request){
    	logger.info("===========appHouseController.list()start============");
    	Result result = new Result();
    	String  districtName= request.getParameter("districtName");//
    	String rentType = request.getParameter("rentType");//
    	String page = request.getParameter("page");
    	String limit = request.getParameter("limit");
    	
    	HouseEntity houseEntity = new HouseEntity();
    	PageUtils pageUtils = new PageUtils();
    	houseEntity.setDistrictName(StringUtils.isNoneBlank(districtName) ? districtName : null);//
    	houseEntity.setRentType(StringUtils.isNotBlank(rentType) ? rentType : null);//
    	if(StringUtils.isNotBlank(limit)) {
    		try {
				int pageSize = Integer.parseInt(limit);
				pageUtils.setPageSize(pageSize > 1 ? pageSize : 10);
			} catch (NumberFormatException e) {
				//忽略此错误，使用默认值
				pageUtils.setPageSize(10);
				logger.error("解析limit出错，请确认传递的limit为数字");
			}
    	}
    	if(StringUtils.isNotBlank(page)) {
    		try {
				int currPage = Integer.parseInt(page);
				pageUtils.setCurrPage(currPage > 1 ? currPage : 1); 
			} catch (NumberFormatException e) {
				//忽略此错误，使用默认值
				pageUtils.setCurrPage(1);
				logger.error("解析page出错，请确认传递的page为数字");
			}
    	}
    	
    	List<HouseEntity> list = null;
		try {
			list = this.houseService.queryAppList(houseEntity,pageUtils);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			logger.error("查询列表出现异常，请联系管理员");
			return Result.error("1","查询房源列表失败，请稍后再试");
		} 	
			//为列表中所有的子房源，添加父房源的图片信息
		if(ValidatorUtils.isNotEmpty(list)) {
			for (HouseEntity entity : list) {
				if(StringUtils.isNotBlank(entity.getParentId())) {
					//子房源
					List<HouseImageEntity> houseImages = this.houseImageService.queryListByHouseId(entity.getParentId());
					if(ValidatorUtils.isEmpty(houseImages)) {
						houseImages = new ArrayList<HouseImageEntity>();
						logger.info("通过房源id:" + entity.getId() + ",未找到对应的房源照片信息");
					}
					entity.setHouseImages(houseImages);
				}
			}
		}
    	pageUtils.setList(list);
    	result.put("page",pageUtils);
    	logger.info("===========appHouseController.list()end============");
        return result;
    }
    
    @RequestMapping(value = "housesOfLandlord", method = RequestMethod.GET)
	@ResponseBody
	@LoginRequired
	public Result housesOfLandlord(HttpServletRequest request, String landlordId) {
    	logger.info("===========appHouseController.housesOfLandlord()start============");
		Result result = new Result();
		if(StringUtils.isBlank(landlordId)) {
			logger.info("房东id不能为空");
			return Result.error("1", "房东id不能为空");
		}
		UserLandlordEntity landlord = landlordService.queryObject(landlordId);
		if(landlord == null) {
			logger.info("通过房东id：" + landlordId + "，未找到对应的房东，请确认房东id的正确性");
			return Result.error("1", "通过房东id：" + landlordId + "，未找到对应的房东，请确认房东id的正确性");
		}
		//添加分頁功能
		String page = request.getParameter("page");
    	String limit = request.getParameter("limit");
    	PageUtils pageUtils = new PageUtils();
    	if(StringUtils.isNotBlank(limit)) {
    		try {
				int pageSize = Integer.parseInt(limit);
				pageUtils.setPageSize(pageSize > 1 ? pageSize : 10);
			} catch (NumberFormatException e) {
				//忽略此错误，使用默认值
				pageUtils.setPageSize(10);
				logger.error("解析limit出错，请确认传递的limit为数字");
			}
    	}
    	if(StringUtils.isNotBlank(page)) {
    		try {
				int currPage = Integer.parseInt(page);
				pageUtils.setCurrPage(currPage > 1 ? currPage : 1); 
			} catch (NumberFormatException e) {
				//忽略此错误，使用默认值
				pageUtils.setCurrPage(1);
				logger.error("解析page出错，请确认传递的page为数字");
			}
    	}
		List<HouseEntity> list = null;
		try {
			list = this.houseService.queryListByLandlordId(landlordId,pageUtils);
		} catch (Exception e) {
			logger.error("查询房东id：" + landlordId + "，名下的房源列表失败");
			logger.error(e.getMessage(),e);
			return Result.error("1", "查询房东id：" + landlordId + "，名下的房源列表失败");
		}
		
		pageUtils.setList(list);
		result.put("page", pageUtils);
		logger.info("===========appHouseController.housesOfLandlord()end============");
		return result;
	}
    
}
